﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using CommonHelp;
using Core.Unity;
using Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Services {
    /// <summary>
    /// 地震
    /// </summary>
    public class EarthquakeInfoService : Core.Unity.IInfoService {
        private EventHandler<ReceivedDataEventArgs> _ReceivedDataEvents;
        private List<EarthquakeInfo> _DataList;

        public event EventHandler<ReceivedDataEventArgs> AfterQueryData {
            add {
                _ReceivedDataEvents += value;
            }
            remove {
                _ReceivedDataEvents -= value;
            }
        }

        public void OnModelCreating(ref DbModelBuilder modelBuilder) {
            modelBuilder.Entity<EarthquakeInfo>().ToTable("WEBDATA_EARTHQUAKE");
        }

        public void QueryData() {
            string url = ConfigurationManager.AppSettings["QueryEarthquakeUrl"].ToString();
            HttpHelper http = new HttpHelper(url);
            http.GetAsync(AfterGetData);
        }

        private void AfterGetData(string responseString) {
            string jsonStr = responseString.Trim(new char[] { ' ', '(', ')' });
            JObject jsObj = JObject.Parse(jsonStr);
            JToken shuju = jsObj["shuju"];
            List<JToken> nodes = shuju.ToList();

            List<EarthquakeInfo> infos = new List<EarthquakeInfo>();
            nodes.ForEach(a => {
                EarthquakeInfo info = JsonConvert.DeserializeObject<EarthquakeInfo>(a.ToString());
                infos.Add(info);
            });

            _DataList = infos;

            if (_ReceivedDataEvents != null) {
                _ReceivedDataEvents(this, new ReceivedDataEventArgs(infos));
            }
        }

        public void SaveData(object data) {
            using (WebDataContext db = new WebDataContext()) {
                List<EarthquakeInfo> list = data as List<EarthquakeInfo>;
                DbSet<EarthquakeInfo> infos = db.Set<EarthquakeInfo>();
                foreach (var item in list) {
                    if (infos.Any(a => a.ID == item.ID)) {
                        continue;
                    }

                    infos.Add(item);
                }
                db.SaveChanges();
            }
        }
    }
}
